// 2025/10/11: 首个版本

using System;
using Avalonia.Input;
using Avalonia.Media;
using ASEva;
using ASEva.UIAvalonia;
using ASEva.Utility;

namespace CommonSource
{
    partial class InputNumberOrString : DialogPanel
    {
        public InputNumberOrString() // For designer
        {
            InitializeComponent();
        }

        public InputNumberOrString(String title, double defaultValue, String iconResourceName = null)
        {
            InitializeComponent();
            SetFixMode(600, 50, true);
            Icon = ResourceLoader.Load(iconResourceName)?.ToAvaloniaWindowIcon();
            Title = title;
            InputValue = defaultValue.ToString();
            entry.Text = InputValue;

            entry.TextChanged += delegate
            {
                double num = 0;
                if (Double.TryParse(entry.Text, out num))
                {
                    entry.Foreground = App.DarkTheme ? Brushes.White : Brushes.Black;
                    button.IsEnabled = true;
                }
                else
                {
                    entry.Foreground = Brushes.Red;
                    button.IsEnabled = false;
                }
            };

            initEvents();
        }

        public InputNumberOrString(String title, String defaultValue, String iconResourceName = null)
        {
            InitializeComponent();
            SetFixMode(600, 50, true);
            Icon = ResourceLoader.Load(iconResourceName)?.ToAvaloniaWindowIcon();
            Title = title;
            InputValue = defaultValue ?? "";
            entry.Text = InputValue;

            if (title.ToLower().Contains("password") || title.Contains("密码"))
            {
                entry.PasswordChar = '●';
            }

            initEvents();
        }

        private void initEvents()
        {
            Loaded += delegate
            {
                entry.Focus();
            };

            entry.KeyDown += (o, e) =>
            {
                if (e.Key == Key.Enter && button.IsEnabled)
                {
                    InputValue = entry.Text;
                    Close();
                }
            };

            button.Click += delegate
            {
                InputValue = entry.Text;
                Close();
            };
        }

        public String InputValue { get; private set; }
    }
}